package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.ShowActivityInfoDto;
import com.aiti.lulian.dto.ShowActivityInfoEnrollDto;
import com.aiti.lulian.dto.ShowActivityInfoEnrollExportDto;
import com.aiti.lulian.dto.ShowActivityInfoExportDto;
import com.aiti.lulian.entity.ShowActivityInfo;
import com.aiti.lulian.entity.ShowActivityInfoEnroll;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.ShowActivityInfoEnrollService;
import com.aiti.lulian.service.ShowActivityInfoService;
import com.aiti.lulian.vo.ShowActivityInfoEnrollVo;
import com.aiti.lulian.vo.ShowActivityInfoVo;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.net.HttpHeaders;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动报名 前端控制器
 * </p>
 *
 * @author 
 * @since
 */
@RestController
@RequestMapping("/activityEnroll")
public class ShowActivityInfoEnrollController extends WebController {

    @Autowired
    private ShowActivityInfoEnrollService activityInfoEnrollService;
    @Autowired
    private CloudShowManagerSubService managerSubService;





    @GetMapping("/detail")
    public Message detail(@RequestParam("baseId") String baseId) {
        return Message.success(activityInfoEnrollService.getActivityEnrollById(baseId));
    }

    @PostMapping
    public Message insert(@RequestBody ShowActivityInfoEnroll entity) {
        entity.setCreator(StrUtil.isNotBlank(entity.getCreator())? entity.getCreator():findUserId());
        activityInfoEnrollService.saveActivityEnroll(entity);
        return Message.success();
    }

    @PutMapping
    public Message update(@RequestBody ShowActivityInfoEnroll entity) {
        entity.setUpdateBy(StrUtil.isNotBlank(entity.getUpdateBy())? entity.getUpdateBy():findUserId());
        activityInfoEnrollService.updateActivityEnroll(entity);
        return Message.success();
    }

    @DeleteMapping
    public Message delete(@RequestParam("baseId") String baseId) {
        activityInfoEnrollService.deleteActivityEnroll(baseId);
        return Message.success();
    }

    @GetMapping("/page")
    public Message page(ShowActivityInfoEnrollDto dto) {
        List<String> userRoleList = managerSubService.getUserRoleList(findUserId());
        if(CollectionUtils.isEmpty(userRoleList) || !userRoleList.contains("1")){
            Message userInfo = managerSubService.getUserInfo(findUserId());
            if(userInfo != null && userInfo.getCode() == MessageCodeConstant.MSG_SUCCESS_CODE){
                Map obj = (Map)userInfo.getObj();
                dto.setCity(String.valueOf(obj.get("city")));
                dto.setCounty(String.valueOf(obj.get("region")));
            }else{
                throw new RuntimeException("获取用户信息有误");
            }
        }

        Page page = this.startPage(dto);
        List<ShowActivityInfoEnrollVo> list = activityInfoEnrollService.listActivityEnroll(page, dto);
        return Message.success(this.getPageResult(list, (int)page.getTotal()));
    }

    @ApiOperation("导出活动报名")
    @GetMapping("/export")
    public void export(HttpServletResponse response, ShowActivityInfoEnrollDto dto) {
        try {
            List<String> userRoleList = managerSubService.getUserRoleList(findUserId());
            if(CollectionUtils.isEmpty(userRoleList) || !userRoleList.contains("1")){
                Message userInfo = managerSubService.getUserInfo(findUserId());
                if(userInfo != null && userInfo.getCode() == MessageCodeConstant.MSG_SUCCESS_CODE){
                    Map obj = (Map)userInfo.getObj();
                    dto.setCity(String.valueOf(obj.get("city")));
                    dto.setCounty(String.valueOf(obj.get("region")));
                }else{
                    throw new RuntimeException("获取用户信息有误");
                }
            }
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("活动报名", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            OutputStream out = response.getOutputStream();

            // 构建 ExcelWriter（整个 Excel 文件）
            ExcelWriter excelWriter = EasyExcel.write(out, ShowActivityInfoEnrollExportDto.class).build();
            // 构建 WriteSheet（具体 sheet）
            WriteSheet writeSheet = EasyExcel.writerSheet("活动报名").registerWriteHandler(new HeaderStyleHandler()).build();

            int pageNum = 1;
            int pageSize = 500;


            List<ShowActivityInfoEnrollExportDto> dataList;


            do {
                Page page = new Page<>(pageNum, pageSize);
                dataList = activityInfoEnrollService.listActivityEnrollForExport(page, dto);


                if (!dataList.isEmpty()) {
                    excelWriter.write(dataList, writeSheet);
                }

                pageNum++;
            } while (!dataList.isEmpty());

            // 关闭 writer（自动关闭流）
            excelWriter.finish();

        } catch (Exception e) {
            logger.error("导出异常：", e);
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }


}
